package com.example.shiro.realm;

import com.example.shiro.entity.Module;
import com.example.shiro.entity.Role;
import com.example.shiro.entity.User;
import com.example.shiro.service.UserService;
import com.example.shiro.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author lijilong
 * @version 1.0
 * @Description:
 * @CreateDate 2018/8/8 8:57
 */
@Slf4j
public class AuthRealm extends AuthorizingRealm{
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("从数据库中获取授权数据");
        User user = (User) principalCollection.getPrimaryPrincipal();
        Set<String> roles = new HashSet<>();
        Set<String> modules = new HashSet<>();
        Set<Role> roleSet = user.getRoles();
        for(Role role : roleSet){
            roles.add(role.getRname());
            Set<Module> moduleSet = role.getModules();
            for(Module module : moduleSet){
                modules.add(module.getMname());
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(modules);
        return info;
    }

    private Set<String> getPermissionByUsername(String username) {
        Set<String> set = new HashSet<>();
        set.add("user:delete");
        set.add("user:update");
        return set;
    }

    private Set<String> getRoleByUsername(String username) {
        Set<String> set = new HashSet<>();
        set.add("admin");
        return set;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        User user = getPassByUsername(username);
        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
        info.setCredentialsSalt(ByteSource.Util.bytes(user.getPasswordSalt()));
        return info;
    }

    private User getPassByUsername(String username) {
        User user = userService.findByUserName(username);
        return user;
    }



}
